package com.antd.auth.filter;

import cn.hutool.core.util.ObjectUtil;
import com.antd.auth.service.UserDetailServiceImpl;
import com.antd.common.auth.exception.AntdCustomOauthException;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * TODO
 *
 * @author 子丶沫
 * @version 1.0
 * @date 2020/12/1 17:35
 */
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {
    private UserDetailServiceImpl userDetailService;
    @Override
    public Authentication authenticate(Authentication authentication) {
        SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken) authentication;
        String mobile = (String) authenticationToken.getPrincipal();
        //调用自定义的userDetailsService认证 通过手机号来查询
        UserDetails userDetails=null;
           try{
               userDetails = userDetailService.loadUserByMobile(mobile);
           }catch (UsernameNotFoundException ex){
               throw new UsernameNotFoundException(ex.getMessage());
           }
        //如果user不为空重新构建SmsCodeAuthenticationToken（已认证）
        assert userDetails != null;
        SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(userDetails, userDetails.getAuthorities());
        authenticationResult.setDetails(authenticationToken.getDetails());
        return authenticationResult;
    }

    /**
     * 只有Authentication为SmsCodeAuthenticationToken使用此Provider认证
     * @param aClass
     * @return
     */
    @Override
    public boolean supports(Class<?> aClass) {
        return SmsCodeAuthenticationToken.class.isAssignableFrom(aClass);
    }

    public UserDetailServiceImpl getUserDetailService() {
        return userDetailService;
    }

    public void setUserDetailService(UserDetailServiceImpl userDetailService) {
        this.userDetailService = userDetailService;
    }
}

